#include <iostream>
#include <cerrno>
#include <unistd.h>
#include <fcntl.h>

void set_nonblock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl == -1)
    {
        std::cerr << "fcntl F_GETFL error: " << errno << std::endl;
        return;
    }

    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

int main()
{
    set_nonblock(0); // set stdin nonblock

    while(true)
    {
        char buffer[128];
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        // On error, -1 is returned, and errno is set appropriately.

        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "get input: " << buffer << std::endl;
        }
        else if(n == 0)
        {
            // ctrl+d or stdin closed
            std::cout << "stdin closed" << std::endl;
            break;
        }
        else
        {
            // error or no data available
            // check if it is a non-blocking error
            if(errno == EWOULDBLOCK || errno == EAGAIN)
            {
                // no data has prepared
                std::cout << "no data available, waiting..." << std::endl;
            }
            else if(errno == EINTR)
            {
                // signal interrupt
                std::cout << "signal interrupt, retry..." << std::endl;
            }
            else
            {
                std::cerr << "read error: " << errno << std::endl;
                break;
            }
        }

        sleep(1); // simulate some work
    }
    return 0;
}